package com.function.base.write;

import com.helper.Utils;
import com.main.tcp.protocol.RequestFrame;
import com.response.ResponseData;

import java.util.List;

/**
 * 批量写寄存器功能基础类
 * @author zhujh
 */
public abstract class BaseWriteMultipleRegisterFunctionAction extends BaseMultipleWriteFunctionAction {


    @Override
    public byte[] getReQuestByte() {
        int registersCount = values.length;
        int bytesCount = registersCount * 2;
        int length = 7 + registersCount * 2;

        super.setLENGTH(length);
        RequestFrame requestFrame = getRequestFrameByFunction()
                .appendData((short)writingAddress)
                .appendData((short)registersCount)
                .appendData((byte)bytesCount);

        for (int value : values) {
            byte[] registerBytes = Utils.toByteArray((short)value);
            requestFrame.appendData((byte)registerBytes[0]);
            requestFrame.appendData((byte)registerBytes[1]);
        }

        return requestFrame.toRequest();
    }


    @Override
    public void validateSendDataParams() {
        super.validDateStartAddress(writingAddress);
        this.validDateValue(values);
    }

    public void validDateValue(int[] values) {
        for (int i = 0; i < values.length ; i++) {
            if (values[i] < 0 && values[i]  > 1) {
                throw new IllegalArgumentException("值只能是0或1");
            }
        }
    }

    @Override
    public List<ResponseData> getResPonseData(byte[] response) {
        return null;
    }

}
